<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

/**
 * App\Models\OrderCommission
 *
 * @property int $id
 * @property int $user_id 用户ID
 * @property int $type 0=洗车订单,1=商城订单
 * @property string|null $order_id 订单编号
 * @property string $amount 订单金额
 * @property string $money 订单结算分成的金额
 * @property int $service 服务ID
 * @property string $service_name 服务名称
 * @property string $card_title 服务名称
 * @property string $platform_rate 平台分成比例
 * @property string $platform_money 平台分成
 * @property int $shop_id 门店ID
 * @property float $shop_rate 门店分成比例
 * @property float $shop_money 门店分成
 * @property int $worker_id 师傅ID
 * @property float $worker_rate 洗车小哥分成比例
 * @property float $worker_money 洗车小哥分成
 * @property int $agent_id 代理商ID
 * @property float $agent_rate 代理商分成比例
 * @property float $agent_money 代理商分成
 * @property int $top_id 上级用户ID
 * @property float $top_rate 上级用户分成比例
 * @property float $top_money 上级用户分成
 * @property int $top_top_id 上上级用户ID
 * @property float $top_top_rate 上上级用户分成比例
 * @property float $top_top_money 上上级用户分成
 * @property string|null $settle_time 结算时间
 * @property int $service_id 服务ID
 * @property-read mixed $price
 * @property int $is_settle 是否已结算:0=未结算,1=已结算,2=已取消
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission query()
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereAgentCityId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereAgentCityRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereAgentDistrictId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereAgentDistrictRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereCityId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereDistrictId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereIsSettle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereOrderId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereProvinceId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereSettleTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereShopId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereShopRate($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereWorkerId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereWorkerRate($value)
 * @mixin \Eloquent
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereAgentCityMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereAgentDistrictMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereServiceId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereServiceName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereShopMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|OrderCommission whereWorkerMoney($value)
 */
class OrderCommission extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'order_commission';

    protected $fillable = [
        'type','service_id','service_name','order_id','amount','shop_id','shop_rate','shop_money',
        'worker_id','worker_rate','worker_money','agent_id','agent_rate','agent_money','platform_rate','platform_money',
        'top_id','top_rate','top_money','top_top_id','top_top_rate','top_top_money','user_id','card_title','shop_id','is_settle'
    ];

    protected static function booted()
    {
       self::updating(function (OrderCommission $row){
           if ($row->is_settle == 1 &&!$row->settle_time){
               $row->settle_time = now()->format("Y-m-d H:i:s");
               OrderCommission::makeCommission($row,  $row->type==1?"商品订单分成":"服务分成");
           }
       });
    }

    /**
     * 新增洗车服务分成记录结算表
     * @param $order_id
     * @param $params
     * @param bool $isOnLyWorker
     * @return void
     */
    public static function addCommission($order_id, $params, bool $isOnLyWorker = false): void
    {
        $data = [
            'type'=>0,'user_id'=>$params['user_id'],'order_id'=>$order_id,'amount'=>$params['amount'],
            'shop_id'=>$params['shop_id'],'worker_id'=>$params['worker_id'],'service_id'=>$params['service_id'],
            'service_name'=>$params['service']['title'],"top_id"=>0,"top_money"=>0,"top_top_money"=>0,"top_top_id"=>0
        ];
        $info = $params['info'];
        $data['worker_rate'] = $info['worker_rate'];
        $data['worker_money'] = floatval($data['worker_rate']);
        if (!$isOnLyWorker){
            $platform_rate = \App\Api\Models\Config::getName("platform_rate");
            $agent_id = $info['agent_id'];
            $amount = floatval($params['amount']);
            $platform_money = round($amount * $platform_rate/100,2);
            //平台分配的金额
            $data['platform_rate'] = $platform_rate;
            $data['platform_money'] = $platform_money;
            $data['top_rate'] = $info['top_rate'];
            $data['top_top_rate'] = $info['top_top_rate'];
            $user = User::query()->where("id",$params['user_id'])->first();
            if ($user&&$user->tid){
                $isMember = UserCard::query()->where("user_id",$user->tid)->exists();
                if ($isMember){
                    $data['top_id'] = $user->tid;
                    $data['top_money'] = round($amount*$info['top_rate']/100,2);
                    $topUser = User::query()->where("id",$user->tid)->first();
                    if ($topUser&&$topUser->tid){
                        $isMember = UserCard::query()->where("user_id",$topUser->tid)->exists();
                        if ($isMember){
                            $data['top_top_id'] = $topUser->tid;
                            $data['top_top_money'] = round($amount*$data['top_top_rate']/100,2);
                        }
                    }
                }
            }
            $data['agent_id'] = $agent_id;
            $data['agent_rate'] = $info['agent_rate'];
            $data['agent_money'] = round($amount*$info['agent_rate']/100,2);
            $shop_money = $amount - ($platform_money + $data['top_money'] + $data['top_top_money'] + $data['agent_money']);
            $data['shop_money'] = $shop_money;
        }
        self::create($data);
    }


    /**
     * 新增洗车卡分成记录结算表
     * @return void
     */
    public static function addCardCommission(UserCard $userCard): void
    {
        $user_id = $userCard->user_id;
        $oid = $userCard->order_id;
        $shop_id = $userCard->shop_id;
        $amount = $userCard->price;
        $shop = ShopUser::query()->where("id",$shop_id)->first();
        $agent_id = $shop->agent_id;
        $agent = AgentUser::query()->where("id",$agent_id)->first();
        $payOrder = PaymentOrder::query()->where("id",$oid)->first();
        $order_id = $payOrder->out_trade_no;
        $data = [
            'type'=>2,'user_id'=>$user_id,'order_id'=>$order_id,'amount'=>$amount,
            'shop_id'=>$shop_id,'worker_id'=>0,"top_id"=>0,"top_money"=>0,
            "top_top_money"=>0,"top_top_id"=>0, 'worker_rate'=>0,'worker_money'=>0,
            "card_title"=>$userCard->title,'agent_rate'=>0, 'agent_money'=>0
        ];
        $extends = $payOrder->extends;
        $card = $extends['card'];
        $rates = $card['rates'];
        $platform_rate = \App\Api\Models\Config::getName("platform_rate");
        $platform_money = round($amount * $platform_rate/100,2);
        //平台分配的金额
        $data['platform_rate'] = $platform_rate;
        $data['platform_money'] = $platform_money;
        $data['agent_id'] = $agent_id;
        $data['top_rate'] = floatval($rates[0]??0);
        $data['top_top_rate'] =floatval($rates[1]??0);
        $user = User::query()->where("id",$user_id)->first();
        if ($user&&$user->tid){
            $isMember = UserCard::query()->where("user_id",$user->tid)->exists();
            if ($isMember){
                $data['top_id'] = $user->tid;
                $data['top_money'] = round($amount*$data['top_rate']/100,2);
                $topUser = User::query()->where("id",$user->tid)->first();
                if ($topUser&&$topUser->tid){
                    $isMember = UserCard::query()->where("user_id",$topUser->tid)->exists();
                    if ($isMember){
                        $data['top_top_id'] = $topUser->tid;
                        $data['top_top_money'] = round($amount*$data['top_top_rate']/100,2);
                    }
                }
            }
        }
        if($agent){
            $agent['agent_rate'] = $agent->agent_rate;
            $agent['agent_money'] = round($amount*$agent['agent_rate']/100,2);
        }
        $shop_money = $amount - ($platform_money + $data['top_money'] + $data['top_top_money'] + $data['agent_money']);
        $data['shop_money'] = $shop_money;
        self::create($data);
    }

    /**
     * 更新结算状态
     */
    public static function updateCommissionOrders($order_no, $desc = "商品订单分成"): void
    {
        $commission = OrderCommission::whereOrderId($order_no)->where("is_settle",0)->first();
        $commission->is_settle = 1;
        $commission->settle_time = now()->format("Y-m-d H:i:s");
        $commission->save();
        OrderCommission::makeCommission($commission,$desc);
    }

    /**
     * 结算分成
     * @param OrderCommission $om
     * @param string $desc
     * @return void
     */
    public static function makeCommission(OrderCommission $om, string $desc = "服务分成"): void
    {
        $shop_money = $om->shop_money;
        $shop_id = $om->shop_id;
        $worker_money = $om->worker_money;
        $worker_id = $om->worker_id;
        $agent_money = $om->agent_money;
        $agent_id = $om->agent_id;
        $top_id = $om->top_id;
        $top_money = $om->top_money;
        $top_top_id = $om->top_top_id;
        $top_top_money = $om->top_top_money;
        if ($shop_money&&$shop_id){
            ShopUser::moneys(1,$shop_id,$shop_money,$desc);
        }
        if ($worker_money&&$worker_id){
            Worker::moneys(1,$worker_id,$worker_money,$desc);
        }
        if ($agent_money&&$agent_id){
            AgentUser::moneys(1,$agent_id,$agent_money,$desc);
        }
        if ($top_money&&$top_id){
            User::amount(1,$top_id,$top_money,$desc);
        }
        if ($top_top_money&&$top_top_id){
            User::amount(1,$top_top_id,$top_top_money,$desc);
        }
    }

    public function shop(){
        return $this->hasOne(ShopUser::class,"id","shop_id");
    }

}
